<template>
  <div class="class-management">
    <!-- 查询区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="班级ID">
            <el-input v-model="filterForm.classId" placeholder="请输入班级ID" @keyup.enter="queryClassDetail" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="justify-content: right;">
            <el-button type="primary" @click="queryClassDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <el-button type="success" @click="addDialogVisible=true">添加班级</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 班级详情对话框 -->
    <el-dialog v-model="queryDialogVisible" title="班级信息查询结果" width="50%" @close="handleQueryDialogClose">
      <el-form :model="queryClassInfo" label-width="120px">
        <el-form-item label="班级ID">
          <el-input v-model="queryClassInfo.classId" disabled></el-input>
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="queryClassInfo.grade" disabled></el-input>
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="queryClassInfo.major" disabled></el-input>
        </el-form-item>
        <el-form-item label="院系">
          <el-input v-model="queryClassInfo.department" disabled></el-input>
        </el-form-item>
        <el-form-item label="班级名字">
          <el-input v-model="queryClassInfo.className" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 班级列表 -->
    <el-card class="class-list-card">
      <div class="table-container">
        <el-table :data="classList" stripe border @row-dblclick="handleRowClick" style="width: 100%;" max-height="500px">
          <el-table-column prop="classId" label="班级ID"></el-table-column>
          <el-table-column prop="grade" label="年级"></el-table-column>
          <el-table-column prop="major" label="专业"></el-table-column>
          <el-table-column prop="department" label="院系"></el-table-column>
          <el-table-column prop="className" label="班级名字"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加班级对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加班级" width="50%" @close="handleAddDialogClose">
      <el-form :model="addForm" ref="addFormRef" label-width="120px" :rules="addFormRules">
        <el-form-item label="班级ID" prop="classId">
          <el-input v-model="addForm.classId"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="addForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="addForm.major"></el-input>
        </el-form-item>
        <el-form-item label="院系" prop="department">
          <el-input v-model="addForm.department"></el-input>
        </el-form-item>
        <el-form-item label="班级名字" prop="className">
          <el-input v-model="addForm.className"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑班级对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑班级" width="50%" @close="handleEditDialogClose">
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="editFormRules">
        <el-form-item label="班级ID" prop="classId">
          <el-input v-model="editForm.classId" disabled></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="editForm.grade"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="editForm.major"></el-input>
        </el-form-item>
        <el-form-item label="院系" prop="department">
          <el-input v-model="editForm.department"></el-input>
        </el-form-item>
        <el-form-item label="班级名字" prop="className">
          <el-input v-model="editForm.className"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 筛选条件
const filterForm = reactive({
  classId: "",
});

// 表格数据和分页
const classList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryClassInfo = ref({
  classId: "",
  grade: "",
  major: "",
  department: "",
  className: "",
});

// 添加班级表单
const addDialogVisible = ref(false);
const addForm = ref({
  classId: "",
  grade: "",
  major: "",
  department: "",
  className: "",
});
const addFormRef = ref(null);

// 编辑班级表单
const editDialogVisible = ref(false);
const editForm =ref({
  classId: "",
  grade: "",
  major: "",
  department: "",
  className: "",
});
const editFormRef = ref(null);

// 添加表单验证规则
const addFormRules = computed(() => ({
  classId: [
    { required: true, message: "请输入班级ID", trigger: "blur" },
  ],
  grade: [
    { required: true, message: "请输入年级", trigger: "blur" },
  ],
  major: [
    { required: true, message: "请输入专业", trigger: "blur" },
  ],
  department: [
    { required: true, message: "请输入院系", trigger: "blur" },
  ],
  className: [
    { required: true, message: "请输入班级名字", trigger: "blur" },
  ],
}));

// 编辑表单验证规则
const editFormRules = computed(() => ({
  grade: [
    { required: true, message: "请输入年级", trigger: "blur" },
  ],
  major: [
    { required: true, message: "请输入专业", trigger: "blur" },
  ],
  department: [
    { required: true, message: "请输入院系", trigger: "blur" },
  ],
  className: [
    { required: true, message: "请输入班级名字", trigger: "blur" },
  ],
}));

// 生命周期钩子
onMounted(async () => {
  await fetchClassList();
});

// 获取班级列表
const fetchClassList = async () => {
  try {
    // const params = {
    //   ...filterForm,
    //   page: currentPage.value,
    //   size: pageSize.value,
    // };
    const formData = new FormData();
    formData.append("classId",filterForm.classId);
    formData.append("page",currentPage.value);
    formData.append("size",pageSize.value);
    const response = await axios.post("/classes/getClassList", formData);
    classList.value = response.data.result || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error("获取班级列表失败", error);
    ElMessage.error("获取班级列表失败，请稍后重试");
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.classId = "";
  fetchClassList();
};

// 添加对话框关闭时处理
const handleAddDialogClose = () => {
  addDialogVisible.value = false;
};

// 提交添加表单
const submitAddForm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = new FormData();
        formData.append('classId',addForm.value.classId);
        formData.append('grade',addForm.value.grade);
        formData.append('major',addForm.value.major);
        formData.append('department',addForm.value.department);
        formData.append('className',addForm.value.className);

        const response = await axios.post("/classes/addClass", formData);
        if (response.data.flag) {
          ElMessage.success("班级添加成功");
          addDialogVisible.value = false;
          addForm.value={};
          fetchClassList();
        } else {
          ElMessage.error(response.data.message || "班级添加失败");
        }
      } catch (error) {
        console.error("添加班级失败", error);
        ElMessage.error("添加班级失败，请稍后重试");
      }
    }
  });
};

// 编辑班级
const handleEdit = (row)=> {
  editDialogVisible.value = true;
  editForm.value={...row};
};

// 编辑对话框关闭时处理
const handleEditDialogClose = () => {
  editDialogVisible.value = false;
  editForm.value={};
};

// 提交编辑表单
const submitEditForm = async () => {
  await editFormRef.value.validate(async (valid) => {
    if (valid) {

      const formData = new FormData();
      formData.append("classId", editForm.value.classId);
      formData.append("grade", editForm.value.grade);
      formData.append("major", editForm.value.major);
      formData.append("department", editForm.value.department);
      formData.append("className", editForm.value.className);

      try {
        const response = await axios.post("/classes/updateClass", formData);
        if (response.data.flag) {
          ElMessage.success("班级信息更新成功");
          editDialogVisible.value = false;
          console.log('班级信息更新成功');
          fetchClassList();
        } else {
          ElMessage.error(response.data.message || "班级信息更新失败");
        }
      } catch (error) {
        console.error("更新班级信息失败", error);
        ElMessage.error("更新班级信息失败，请稍后重试");
      }
    }
  });
};

// 删除班级
const handleDelete = (classInfo) => {
  ElMessageBox.confirm(
      `确定要删除班级 "${classInfo.className}" (${classInfo.classId}) 吗？删除后将无法恢复。`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      }
  ).then(async () => {
    try {
      const response = await axios.delete(`/classes/deleteClass?classId=${classInfo.classId}`);
      if (response.data.flag) {
        ElMessage.success("班级删除成功");
        fetchClassList();
      } else {
        ElMessage.error(response.data.message || "班级删除失败");
      }
    } catch (error) {
      console.error("删除班级失败", error);
      ElMessage.error("删除班级失败，请稍后重试");
    }
  }).catch(() => {
    // 取消操作
  });
};

// 双击行编辑
const handleRowClick = (row) => {
  handleEdit(row.classId);
};

// 分页控制
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchClassList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchClassList();
};

// 单独的班级查询方法
const queryClassDetail = async () => {
  const classId = filterForm.classId;

  if (!classId) {
    ElMessage.warning("请输入班级ID");
    return;
  }

  try {
    const response = await axios.get(`/classes/getClassDetail?classId=${classId}`);
    if (response.data.flag) {
      queryClassInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || "查询失败");
    }
  } catch (error) {
    console.error("查询出错:", error);
    ElMessage.error("查询时发生错误，请稍后重试");
  }
};

// 查询对话框关闭时处理
const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryClassInfo.value = {
    classId: "",
    grade: "",
    major: "",
    department: "",
    className: "",
  };
};
</script>

<style scoped>
.class-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.class-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>